#include "stdafx.h"
#include "road_node_maker.h"
#include "clientinterfaces.h"
#include <iltclient.h>
#include "ltclientshell.h"
#include "Screen/tex_mgr.h"
#include <fstream>
road_node_maker& road_node_maker::single()
{
	static road_node_maker _single;
	return _single;
}

road_node_maker::road_node_maker():
m_car(0),
m_active(false)
{
	m_nodes.reserve(100);

}

void road_node_maker::update()
{
	if (!m_active)
	{
		return;
	}
	if (!m_car)
	{
		m_car=g_pLTClient->GetClientObject();
	}
	if (!m_tex)
	{
		m_tex=tex_mgr::single().get_tex("Dir");
	}
	g_pLTCDrawPrim->SetTransformType(DRAWPRIM_TRANSFORM_WORLD);
	g_pLTCDrawPrim->SetZBufferMode(DRAWPRIM_ZRW);
	g_pLTCDrawPrim->SetColorOp(DRAWPRIM_MODULATE);
	g_pLTCDrawPrim->SetTexture(m_tex);
	
	LTVector _pos;
	LTRotation _rot;
	g_pLTClient->GetObjectPos(m_car,&_pos);
	g_pLTClient->GetObjectRotation(m_car,&_rot);
	m_current_node.set_trans(_pos,_rot);
	m_current_node.render();

	for (std::vector<road_node>::iterator it =m_nodes.begin();
		it!=m_nodes.end();++it)
	{
		g_pLTCDrawPrim->SetTexture(m_tex);
		it->render();
	}

}

void road_node_maker::add_node()
{
	static bool  cc;
	m_nodes.push_back(m_current_node);
	if (cc)
	{
		m_nodes.back().set_color();
	}
	else
		m_nodes.back().set_color(150,0,0,150);
	m_nodes.back().set_trans(m_current_node.get_pos()+m_current_node.get_rot().Up()*0.2f,m_current_node.get_rot());
	cc=!cc;


}

void road_node_maker::cancel_last()
{
	if (m_nodes.empty())
	{
		return;
	}
	m_nodes.pop_back();
}

void road_node_maker::save_to_file( const char* _file_name )
{
	std::fstream fileout(_file_name, std::ios::trunc | std::ios::out) ;
	try
	{
		fileout<<m_nodes.size()<<std::endl;
		for (int i=0;i<m_nodes.size();++i)
		{
			fileout<<m_nodes[i].get_pos().x<<" "<<m_nodes[i].get_pos().y<<" "<<m_nodes[i].get_pos().z<<" "<<std::endl;
			fileout<<m_nodes[i].get_rot().Forward().x<<" "<<m_nodes[i].get_rot().Forward().y<<" "<<m_nodes[i].get_rot().Forward().z<<" "<<std::endl;
			fileout<<m_nodes[i].get_rot().Up().x<<" "<<m_nodes[i].get_rot().Up().y<<" "<<m_nodes[i].get_rot().Up().z<<" "<<std::endl;
		
		}
	}catch(...)
	{
		fileout.close();
	}




}